import React, { useEffect, useMemo, useState } from "react";
import { WDHeader } from "../../../components";
import style from "./style.module.scss";
import { useRequest, useSetState } from "ahooks";
import { getDiseaseListById, getDiseaseTitle } from "../../../api/diseaseApi";
import { addClassName } from "../../../utils";
import { useSearchParams } from "react-router-dom";
import { WDDiseaseItem } from "../../../components/wd-disease-item";
import { List } from "react-vant";
export interface DiseaseTitleState {
  departmentName: string;
  id: number;
  pic: string;
  rank: number;
}

export interface DiseaseContentState {
  amount: number;
  collectionNum: number;
  commentNum: number;
  detail: string;
  releaseTime: number;
  sickCircleId: number;
  title: string;
}

const Index = () => {
  // 获取 查询参数hooks
  const [searchParams, setSearchParams] = useSearchParams();
  // 获取查询参数 id
  const id = +searchParams.get("id")!;
  // 请求数据 标题
  const { data: diseaseTitleData = [] } = useRequest(async () => {
    const resp = await getDiseaseTitle();
    // 判断 如何路径上 存在id 那么就根据这个id获取列表数据和切换高亮
    // id 不存在  去标题第一项id 作为路径的上的id
    if (!id) setSearchParams({ id: resp.result[0].id });
    return resp.result as DiseaseTitleState[];
  });
  // 请求参数
  const [param, setParams] = useSetState({
    count: 10,
    page: 1,
    departmentId: id,
  });
  // 列表
  const [list, setList] = useState<DiseaseContentState[]>([]);

  // 副作用 请求参数变化， 重新请求数据
  const fetchList = async () => {
    const resp = await getDiseaseListById(param);
    if(param.page === 1) {
      setList(resp.result);
    } else {
      setList([...list, ...resp.result]);
    }
    setParams({ page: param.page + 1 });
  };

  useEffect(() => {
    fetchList()
  }, [param.departmentId])

  return (
    <div>
      <WDHeader showSearch={false}></WDHeader>

      <div className={style.title}>
        {diseaseTitleData.map((v) => {
          return (
            <span
              className={
                id === v.id
                  ? addClassName(style.span, style.active)
                  : style.span
              }
              key={v.id}
              onClick={() => {
                setSearchParams({ id: v.id + "" });
                setParams({
                  page: 1,
                  departmentId: v.id
                })                
              }}
            >
              {v.departmentName}
            </span>
          );
        })}
      </div>

      <List className={style.content} onLoad={fetchList}>
        {list.map((v) => {
          return <WDDiseaseItem key={v.sickCircleId} v={v}></WDDiseaseItem>;
        })}
      </List>
    </div>
  );
};

export default Index;
